using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UwinEducation.Application.Common.Exceptions;
using UwinEducation.Application.Common.Interfaces;
using UwinEducation.Application.Dtos;
using UwinEducation.Domain.Entities;
using UwinEducation.Domain.IRepositories;

namespace UwinEducation.Application.Services
{
    /// <summary>
    /// 系统配置服务实现
    /// </summary>
    public class SystemConfigService : ISystemConfigService
    {
        private readonly ISystemConfigRepository _configRepository;
        private readonly IMapper _mapper;

        
        public SystemConfigService(
            ISystemConfigRepository configRepository,
            IMapper mapper)
        {
            _configRepository = configRepository;
            _mapper = mapper;
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<SystemConfigDto>> GetAllAsync()
        {
            var configs = await _configRepository.GetAllAsync();
            return _mapper.Map<IEnumerable<SystemConfigDto>>(configs);
        }


        /// <inheritdoc/>
        public async Task<SystemConfigDto> GetByKeyAsync(string key)
        {
            var config = await _configRepository.GetByKeyAsync(key);
            if (config == null)
                return null;
                
            return _mapper.Map<SystemConfigDto>(config);
        }

        /// <inheritdoc/>
        public async Task<string> GetValueByKeyAsync(string key)
        {
            return await _configRepository.GetValueByKeyAsync(key);
        }





        ///// <inheritdoc/>
        //public async Task<SystemConfigDto> CreateAsync(CreateSystemConfigDto createDto)
        //{
        //    // 检查键是否已存在
        //    var existingConfig = await _configRepository.GetByKeyAsync(createDto.Key);
        //    if (existingConfig != null)
        //        throw new DuplicateKeyException($"配置键 '{createDto.Key}' 已存在");
                
        //    var config = new SystemConfig
        //    {
        //        Id = Guid.NewGuid(),
        //        Key = createDto.Key,
        //        Value = createDto.Value,
        //        Description = createDto.Description,
        //        CreatedAt = DateTime.Now
        //    };
            
        //    await _configRepository.AddAsync(config);
        //    return _mapper.Map<SystemConfigDto>(config);
        //}

        /// <inheritdoc/>
        public async Task<SystemConfigDto> UpdateAsync(UpdateSystemConfigDto updateDto)
        {
            var config = await _configRepository.GetByKeyAsync(updateDto.Key);
            if (config == null)
            {
                config = SystemConfig.Create(updateDto.Key, updateDto.Value, updateDto.Description);
                await _configRepository.AddAsync(config);

            }
            else
            {
                // 检查行版本是否匹配（乐观并发控制）
                //if (updateDto.RowVersion != null && !config.RowVersion.SequenceEqual(updateDto.RowVersion))
                //    throw new ConcurrencyException(nameof(SystemConfig), updateDto.Key);
                config.Value = updateDto.Value;
                if (updateDto.Description != null)
                    config.Description = updateDto.Description;

                config.UpdatedAt = DateTime.Now;

                await _configRepository.UpdateAsync(config);
            }
                

            return _mapper.Map<SystemConfigDto>(config);
        }


    }
} 